﻿using Approve.BLL;
using Approve.Web.Models.Shared;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http.Filters;

namespace Approve.Web.Models.Filter
{
    /// <summary>
    /// 捕获全局异常Filter
    /// </summary>
    public class CatchGlobalExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            var excep = ExceptionHelper.Throw(context.Exception.Message);

            if (context.Exception is ExceptionHelper)
            {
                excep = context.Exception as ExceptionHelper;
            }
            else
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                ///logger.Debug("调试1111111111");
                logger.Error(context.Exception.StackTrace);
            }
            var json = ApproveResponse.Format(excep, "");
            var jsonText = JsonHelper.ObjectToJSON(json);
            context.Response = new HttpResponseMessage()
            {
                Content = new StringContent(jsonText)
            };
            context.Response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
            base.OnException(context);
        }
    }
}